/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY. 
 * See the GNU General Public License for more details.
 * 
 * Copyright (C) 2011 CellObject.net
 */
package net.cellobject.javacodeformatter.action;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import net.cellobject.javacodeformatter.Formatter;
import net.cellobject.javacodeformatter.model.FormatterManager;
import net.cellobject.javacodeformatter.model.IFormatterItem;
import net.cellobject.javacodeformatter.util.FileUtil;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;

public class FormatAllFilesActionDelegate implements IObjectActionDelegate {
	private IWorkbenchPart targetPart;

	public FormatAllFilesActionDelegate() {
		super();
	}

	public void setActivePart(final IAction action, final IWorkbenchPart targetPart) {
		this.targetPart = targetPart;
	}

	public void run(final IAction action) {
		final ISelection selection = targetPart.getSite().getPage().getSelection();
		final IStructuredSelection structuredSelection = ((IStructuredSelection)selection);
		final IResource resource = (IResource)structuredSelection.getFirstElement();
		final IProject project = resource.getProject();
		final IWorkbenchPage page = targetPart.getSite().getWorkbenchWindow().getActivePage();
		final Collection<IResource> itemsToAdd = new HashSet<IResource>();
		final List<IResource> resources = FileUtil.getAllProjectFiles(project);
		for (final IResource projectResource : resources) {
			if ( (projectResource instanceof IFile) && (projectResource.toString().endsWith(".java"))) {
				itemsToAdd.add(projectResource);								
			}
		}
		// Add all java files to Formatter list
		if (itemsToAdd.size() > 0) {
			FormatterManager.getManager().addFavorites(itemsToAdd.toArray());
		}
		//Loop through all java elements in Formatter list	
		final IFormatterItem[] items = FormatterManager.getManager().getFavorites();
		//Format files
		Formatter.getTPFormatter().formatFiles(page, items);
		//Remove Formatter items
		FormatterManager.getManager().removeFavorites(items);
	}

	public void selectionChanged(final IAction action, final ISelection selection) {
	}
}
